/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.product;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.core.util.QRcodeUtils;
import shop.services.front.favorite.FavoriteService;
import shop.services.front.favorite.bean.Favorite;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.orderdetail.OrderdetailService;
import shop.services.front.orderdetail.bean.Orderdetail;
import shop.services.front.product.ProductService;
import shop.services.front.product.bean.Product;
import shop.services.front.productuser.ProductuserService;
import shop.services.front.productuser.bean.Productuser;
import shop.services.front.spec.SpecService;
import shop.services.front.spec.bean.Spec;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @类名称：ProductController
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:50:43
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/front/product/")
public class ProductController extends FrontBaseController<Product> {
    private final static String PRODUCT_FAVORITE_YES = "y";
    private final static String ADDRESS_FAVORITE_NO = "n";
    @Resource
    private ProductService productService;
    @Resource
    private SpecService specService;
    @Resource
    private FavoriteService favoriteService;
    @Resource
    private OrderdetailService orderdetailService;
    @Resource
    private OrderService orderService;
    @Resource
    private UserService userService;
    @Resource
    private ProductuserService productuserService;

    @Override
    public Services<Product> getService() {
        return productService;
    }


    /**
     * 跳转到开团列表页面
     *
     * @return
     */
    @RequestMapping("toProductList")
    public String toProductList() {
        return "/front/group/openGroup";
    }

    /**
     * 跳转到开团详情页面
     *
     * @return
     */
    @RequestMapping("toProductDetail")
    public String toProductDetail() {
        return "/front/group/productDetail";
    }


    /**
     * 跳转到添加商品页面
     *
     * @return
     */
    @RequestMapping("toAddProduct")
    public String toAddProduct() {
        return "/front/group/addProduct";
    }

    /**
     * 跳转到编辑开团页面
     *
     * @return
     */
    @RequestMapping("toEditProduct")
    public String toEditProduct() {
        return "/front/group/editProduct";
    }

    /**
     * 跳转到团购列表页面
     *
     * @return
     */
    @RequestMapping("toGroupPurchase")
    public String toGroupPurchase() {
        return "/front/group/groupPurchase";
    }


    /**
     * 跳转到商品审核详情页面
     *
     * @return
     */
    @RequestMapping("toProductCheckDetail")
    public String toProductCheckDetail() {
        return "/front/group/productCheckDetail";
    }

    /**
     * 跳转到商品审核页面
     *
     * @return
     */
    @RequestMapping("toProductCheck")
    public String toProductCheck() {
        return "/front/group/productCheck";
    }


    /**
     * 跳转到分享页面
     *
     * @return
     */
    @RequestMapping("toShare")
    public ModelAndView toShare(HttpServletRequest request) {
        logger.debug("跳转到分享页面: " + request.getRequestURI() + "?shareID=" + request.getParameter("shareID"));
        User user = (User) request.getSession().getAttribute("userInfo");
        if (!StringUtils.isBlank(request.getParameter("shareID"))) {
            String[] shareIDs = request.getParameter("shareID").split("_");
            Productuser productuser=new Productuser();
            Productuser productuser2=new Productuser();
            Productuser rs=new Productuser();
            Productuser rs2=new Productuser();
            productuser.setUserID(shareIDs[0]);
            productuser2.setUserID(user.getId());
            productuser2.setPid(shareIDs[0]);
            productuser.setProductID(shareIDs[1]);
            productuser2.setProductID(shareIDs[1]);
            rs.setUserID(shareIDs[0]);
            rs2.setUserID(user.getId());
            rs.setProductID(shareIDs[1]);
            rs2.setProductID(shareIDs[1]);
            rs=productuserService.selectOne(rs);
            rs2=productuserService.selectOne(rs2);
            if(rs==null){
                productuserService.insert(productuser);
            }
            if(rs2==null){
                productuserService.insert(productuser2);
            }
        }
        ModelAndView modelAndView = new ModelAndView("/front/group/groupPurchase");
        return modelAndView;
    }


    /**
     * 查询开团列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectProductList")
    @ResponseBody
    public JSONResult selectProductList(HttpSession session, Product product) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) session.getAttribute("userInfo");
        product.setMerchantID(user.getId());
        List<Product> rsList = productService.selectProductList(product);
        for (int i = 0; i < rsList.size(); i++) {
            Spec spec = new Spec();
            spec.setProductID(rsList.get(i).getId());//获取rsList的第i+1个元素
            List<Spec> specList = specService.selectList(spec);
            rsList.get(i).setSpecs(specList);//把字段specs存入商品
        }
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询即将开团列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectPassProduct")
    @ResponseBody
    public JSONResult selectPassProduct(Product product) throws Exception {
        jsonResult = new JSONResult();
        List<Product> rsList = productService.selectList(product);
        for (int i = 0; i < rsList.size(); i++) {
            Spec spec = new Spec();
            spec.setProductID(rsList.get(i).getId());//获取rsList的第i+1个元素
            List<Spec> specList = specService.selectList(spec);
            rsList.get(i).setSpecs(specList);//把字段specs存入商品
            //添加预定团购人数
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setProductID(rsList.get(i).getId());
            List<Orderdetail> orderdetailList = orderdetailService.selectHistoryOrderdetail(orderdetail);
            List<Order> orderList = new ArrayList<>();
            for (Orderdetail orderdetailInfo : orderdetailList) {
                Order order = new Order();
                order.setId(orderdetailInfo.getOrderID());
                order = orderService.selectOne(order);
                if ("y".equals(order.getIsGroup()) && order.getGroupNumber() != 0
                        && "pass".equals(order.getStatus()) && "y".equals(order.getIsReserve())) {
                    orderList.add(order);
                }
            }
            rsList.get(i).setReserveNumber(orderList.size());
        }
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询团购列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectGroupProductList")
    @ResponseBody
    public JSONResult selectGroupProductList(HttpServletRequest request, @ModelAttribute("product") Product product) throws Exception {
        jsonResult = new JSONResult();
        List<Product> rsList = productService.selectGroupProductList(product);
        for (int i = 0; i < rsList.size(); i++) {
            Spec spec = new Spec();
            spec.setProductID(rsList.get(i).getId());//获取rsList的第i+1个元素
            List<Spec> specList = specService.selectList(spec);
            rsList.get(i).setSpecs(specList);//把字段specs存入商品
        }
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询商品列表(销量排序)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectProductListBySellCount")
    @ResponseBody
    public JSONResult selectProductListBySellCount(HttpServletRequest request, @ModelAttribute("product") Product product) throws Exception {
        jsonResult = new JSONResult();
        List<Product> rsList = productService.selectProductListBySellCount(product);
        for (int i = 0; i < rsList.size(); i++) {
            Spec spec = new Spec();
            spec.setProductID(rsList.get(i).getId());//获取rsList的第i+1个元素
            List<Spec> specList = specService.selectList(spec);
            rsList.get(i).setSpecs(specList);//把字段specs存入商品
        }
        jsonResult.setData(rsList);
        return jsonResult;
    }


    /**
     * 查询商品详情
     *
     * @param product
     * @return
     */
    @RequestMapping(value = "selectProductDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectProductDetail(HttpServletRequest request, Product product) {
        JSONResult jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        Product productInfo = productService.selectOne(product);
        //查询产品规格库存列表
        Spec spec = new Spec();
        spec.setProductID(product.getId());
        List<Spec> specs = specService.selectList(spec);
        productInfo.setSpecs(specs);
        //赋值，用户收藏状态
        Favorite favorite = new Favorite();
        favorite.setProductID(product.getId());
        favorite.setUserID(user.getId());
        if (favoriteService.selectOne(favorite) != null) {
            productInfo.setFavoriteStatus(PRODUCT_FAVORITE_YES);
        } else {
            productInfo.setFavoriteStatus(ADDRESS_FAVORITE_NO);
        }
        jsonResult.setData(productInfo);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询订单详情（商品详情入口）
     *
     * @param spec
     * @return
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderDetail(Spec spec) {
        jsonResult = new JSONResult();
        spec = specService.selectOne(spec);
        jsonResult.setData(spec);
        return jsonResult;
    }

    /**
     * 添加商品(开团)
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "insertProduct", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertProduct(HttpSession session, Product product) throws Exception {
        User user = (User) session.getAttribute("userInfo");
        if ("2".equals(user.getRid())) {
            if ("y".equals(product.getIsSelf())) {
                product.setCheckStatus("4");
            } else {
                product.setCheckStatus("2");
            }
        }
        jsonResult = new JSONResult();
        product.setMerchantID(user.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(new Date());
        startTime = startTime.substring(0, 10);
        startTime = startTime + " 23:59:59";
        String startDate = product.getStartDate();
        String sendDate = product.getSendDate();
        //判断送货时间是否大于开团时间
//        if(sendDate.compareTo(startDate)<0){
//            jsonResult.setSuccess(false);
//            jsonResult.setMessage("送货时间不得小于开团时间，请重新填写！");
//            return jsonResult;
//        }
        if (startDate.compareTo(startTime) > 0) {
            int productID = productService.insert(product);
            //添加商品规格
            String[] specCombinations = product.getSpecCombination().split(",");
            String[] specStocks = product.getSpecStock().split(",");
            String[] specPurchasePrices = product.getSpecPurchasePrice().split(",");
            String[] specNowPrices = product.getSpecNowPrice().split(",");
            String[] specGroupPrices = product.getSpecGroupPrice().split(",");
            for (int i = 0; i < specCombinations.length; i++) {
                Spec spec = new Spec();
                spec.setProductID(String.valueOf(productID));
                spec.setSpecCombination(specCombinations[i]);
                spec.setSpecStock(Integer.parseInt(specStocks[i]));
                spec.setSpecPurchasePrice(new BigDecimal(specPurchasePrices[i]));
                spec.setSpecNowPrice(new BigDecimal(specNowPrices[i]));
                spec.setSpecGroupPrice(new BigDecimal(specGroupPrices[i]));
                specService.insert(spec);
            }
            return jsonResult;
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("您的申请日期不符合要求，请提前一天申请开团！");
            return jsonResult;
        }
    }


    /**
     * 编辑商品
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateProduct", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateProduct(Product product) throws Exception {
        jsonResult = new JSONResult();
        //删除旧规格
        Spec spec = new Spec();
        spec.setProductID(product.getId());
        List<Spec> specList = specService.selectList(spec);
        for (Spec specInfo : specList) {
            specService.delete(specInfo);
        }
        //更新商品信息
        productService.update(product);
        //添加商品规格
        String[] specCombinations = product.getSpecCombination().split(",");
        String[] specStocks = product.getSpecStock().split(",");
        String[] specPurchasePrices = product.getSpecPurchasePrice().split(",");
        String[] specNowPrices = product.getSpecNowPrice().split(",");
        String[] specGroupPrices = product.getSpecGroupPrice().split(",");
        for (int i = 0; i < specCombinations.length; i++) {
            Spec specInformation = new Spec();
            specInformation.setProductID(product.getId());
            specInformation.setSpecCombination(specCombinations[i]);
            specInformation.setSpecStock(Integer.parseInt(specStocks[i]));
            specInformation.setSpecPurchasePrice(new BigDecimal(specPurchasePrices[i]));
            specInformation.setSpecNowPrice(new BigDecimal(specNowPrices[i]));
            specInformation.setSpecGroupPrice(new BigDecimal(specGroupPrices[i]));
            specService.insert(specInformation);
        }
        return jsonResult;
    }

    /**
     * 单个审核开团商品
     */
    @RequestMapping(value = "CheckProduct", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult CheckProduct(Product product) throws Exception {
        JSONResult jsonResult = new JSONResult();
        productService.update(product);
        User seller = new User();
        seller.setId(product.getMerchantID());
        seller = userService.selectOne(seller);
        //开团审核结果消息通知
        Map<String, String> msgParam = new HashMap<>();
        msgParam.put("first", "恭喜您，您的商品已通过管理员审核！");
        msgParam.put("keyword1", product.getCheckStatus());
        msgParam.put("keyword2", product.getUpdateTime());
        msgParam.put("remark", "--");
        WxMsgUtil.sendProductCheckMsg(msgParam, systemManager, seller.getOpenID());
        return jsonResult;
    }

    /**
     * 生成商品二维码
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "createProductQRcode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult createProductQRcode(HttpServletRequest request, String shareID) throws Exception {
        JSONResult jsonResult = new JSONResult();
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        String contents = systemManager.getSystemSetting().getWww() + "/rest/front/product/toShare?shareID=" + shareID;
        jsonResult.setData(qrCodeUtils.createQrcode(request, contents));
        return jsonResult;
    }

    /**
     * 生成二维码背景图
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "createBackgroundQrCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult createBackgroundQrCode(HttpServletRequest request, String shareID, String background) throws Exception {
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        String iconUrl = qrCodeUtils.getIconByUrl(request, background);
        logger.debug("背景图url: " + iconUrl);
        String contents = systemManager.getSystemSetting().getWww() + "/rest/front/voucher/toGetVoucher?shareID=" + shareID;
        String backgroundQrCode = qrCodeUtils.createBackgroundQrCode(request, contents, iconUrl);
        logger.debug("生成二维码背景图: " + backgroundQrCode);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(backgroundQrCode);
        return jsonResult;
    }

    /**
     * 查询用户返利等级
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "selectUserRank", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectUserRank(Productuser productuser) throws Exception {
        JSONResult jsonResult = new JSONResult();
        productuser=productuserService.selectOne(productuser);
        if(productuser==null){
            jsonResult.setData(0);
        }else{
            jsonResult.setData(productuser.getRank());
        }
        return jsonResult;
    }

    /**
     * 查询商品分享价格
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "selectProductRank", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectProductRank(Productuser productuser) throws Exception {
        JSONResult jsonResult = new JSONResult();
        //查询商品
        Product product =new Product();
        product.setId(productuser.getProductID());
        product=productService.selectOne(product);
        productuser=productuserService.selectOne(productuser);
        String userRank="0";
        if(productuser!=null)
            userRank=productuser.getRank();
        Spec spec=new Spec();
        spec.setProductID(product.getId());
        List<Spec> specList=specService.selectList(spec);
        BigDecimal price=specList.get(0).getSpecGroupPrice();
        List<BigDecimal> productRank=new ArrayList<>();
        productRank.add(product.getFirstPercent().multiply(price));
        productRank.add(product.getSecondPercent().multiply(price));
        productRank.add(product.getThirdPercent().multiply(price));
        productRank.add(product.getThirdPercent().multiply(price));
        Product productInfo=new Product();
        productInfo.setUserRank(userRank);
        productInfo.setPriceList(productRank);
        jsonResult.setData(productInfo);
        return jsonResult;
    }
}
